//
//  AppDelegate.m
//  easystudy
//
//  Created by kane on 15/6/1.
//  Copyright (c) 2015年 kane. All rights reserved.
//

#import "AppDelegate.h"
#import "TabbarViewController.h"
#import <SMS_SDK/SMS_SDK.h>

#define SMSAppKey @"7e1a5d2485ba"
#define SMSAppSecret @"b0807e5674a0fed9a4d46e8c0ff7d3fa"
#define BMKAppKey @"uOiLe8GRmA5ufEBRGBVAr2YsGwwWSA7e"
//#define BMKAppKey @"iTDRN3SmIuDOQK9Z6nUXoee0xtQAtFPY"

BMKMapManager *_mapManager;
BMKLocationService *_locService;
BMKGeoCodeSearch *_geocodesearch;
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    TabbarViewController *tabbarVC = [[TabbarViewController alloc] init];

    self.navVC = [[UINavigationController alloc] initWithRootViewController:tabbarVC];
    
    self.navVC.navigationBarHidden = YES;
    self.window.rootViewController = self.navVC;
    [self.window makeKeyAndVisible];
    
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"lastUserName"]) {
        [[UserEntity sharedUser] loginSMS:[[NSUserDefaults standardUserDefaults] objectForKey:@"lastUserName"]];
    }
    
    [application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    [application setStatusBarStyle:UIStatusBarStyleDefault];
//    [SMS_SDK registerApp:SMSAppKey withSecret:SMSAppSecret];
    // 要使用百度地图，请先启动BaiduMapManager
    
    _mapManager = [[BMKMapManager alloc]init];
    BOOL ret = [_mapManager start:BMKAppKey generalDelegate:nil];
    if (!ret) {
        NSLog(@"baidu map api: ---------- ------manager start failed!");
    }
    
    //设置定位精确度，默认：kCLLocationAccuracyBest
    [BMKLocationService setLocationDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    //指定最小距离更新(米)，默认：kCLDistanceFilterNone
    //[BMKLocationServicesetLocationDistanceFilter:100.f];
    // 利用百度地图api定位
    //初始化BMKLocationService
    
    _locService = [[BMKLocationService alloc]init];
    _locService.delegate = self;
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];
    _geocodesearch.delegate = self;
//    http://api.map.baidu.com/geocoder?location=32.094250,118.789592&output=json&key=rOREe21NrwdiSHepQSxqz0QG
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess:) name:NotificationLoginSuccess object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(logoutSuccess:) name:NotificationLogoutSuccess object:nil];
    // Override point for customization after application launch.
    
//    [WXApi registerApp:@"wxd930ea5d5a258f4f" withDescription:@"demo 2.0"];
    
    return YES;
}

- (void)loginSuccess:(NSNotification *)notify
{
//    TabbarViewController *tabbarVC = [[TabbarViewController alloc] init];
//    [self.navVC pushViewController:tabbarVC animated:YES];
}
- (void)logoutSuccess:(NSNotification *)notify
{
    [self.navVC popToRootViewControllerAnimated:YES];
}

//- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
////    return  [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
//}

//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
////    return [WXApi handleOpenURL:url delegate:[WXApiManager sharedManager]];
//}

							
- (void)applicationWillResignActive:(UIApplication *)application
{
    [[UIScreen mainScreen] setBrightness:[[[NSUserDefaults standardUserDefaults] objectForKey:@"OriginalBright"] floatValue]];
    [BMKMapView willBackGround];// 百度地图api
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [_locService stopUserLocationService];
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%f",[UIScreen mainScreen].brightness] forKey:@"OriginalBright"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [BMKMapView willBackGround];//百度地图api
    [_locService startUserLocationService];
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}

- (void)onGetNetworkState:(int)iError
{
    if (0 == iError) {
        NSLog(@"联网成功");
    }
    else{
        NSLog(@"onGetNetworkState %d",iError);
    }
    
}

- (void)onGetPermissionState:(int)iError
{
    if (0 == iError) {
        NSLog(@"授权成功");
    }
    else {
        NSLog(@"onGetPermissionState %d",iError);
    }
}

#pragma mark - BMKLocationServiceDelegate
//实现相关delegate 处理位置信息更新
//处理方向变更信息
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    NSLog(@"heading is %@",userLocation.heading);
}


//处理位置坐标更新
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    CLLocationCoordinate2D pt = (CLLocationCoordinate2D){0, 0};
    if (_locService.userLocation.location.coordinate.longitude!= 0
        && _locService.userLocation.location.coordinate.latitude!= 0) {
        //如果还没有给pt赋值,那就将当前的经纬度赋值给pt
        [_locService stopUserLocationService];
        
        pt = (CLLocationCoordinate2D){_locService.userLocation.location.coordinate.latitude,
            _locService.userLocation.location.coordinate.longitude};
    }
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];//初始化反编码请求
    reverseGeocodeSearchOption.reverseGeoPoint = pt;
    [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
    [UserEntity sharedUser].Latitude = [NSString stringWithFormat:@"%g",userLocation.location.coordinate.latitude];
    [UserEntity sharedUser].Longitude = [NSString stringWithFormat:@"%g",userLocation.location.coordinate.longitude];
    
}
-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    if (!error) {
        [UserEntity sharedUser].CityName = result.addressDetail.city;
        [UserEntity sharedUser].ProvinceName = result.addressDetail.province;
        
    }
}

@end
